package com.zkingsoft.actions.admin;

import java.io.IOException;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zkingsoft.actions.common.BaseController;
import com.zkingsoft.anotations.RemoveRequestToken;
import com.zkingsoft.anotations.SaveRequestToken;
import com.zkingsoft.constance.Dictionary;
import com.zkingsoft.constance.SystemConstance;
import com.zkingsoft.model.Bug;
import com.zkingsoft.model.BugFlow;
import com.zkingsoft.model.Users;
import com.zkingsoft.plugin.pojo.PaginationVO;
import com.zkingsoft.plugin.util.WebUtil;
import com.zkingsoft.pojo.AjaxResult;
import com.zkingsoft.services.BugFlowService;
import com.zkingsoft.services.BugService;
import com.zkingsoft.services.UsersService;
import com.zkingsoft.services.impl.BugServiceImpl;
import com.zkingsoft.thread.SendBugMsgsThread;

/**
 * bug管理
 * 
 * @author 谷春霞
 * @date 2016-11-09 14:37
 */
@Controller
@RequestMapping(value = "admin/bug")
public class BugController extends BaseController {

	@Resource
	private BugService currentService;
	@Resource
	private BugFlowService bugFlowService;
	@Resource
	private UsersService usersService;

	/**
	 * 列表显示
	 */
	@RequestMapping(value = "/showList")
	public @ResponseBody
	AjaxResult showList(Bug bug, PaginationVO pageVo) {
		return showList(currentService, bug, pageVo);
	}

	/**
	 * 新增或者修改页面
	 */
	@RemoveRequestToken
	@RequestMapping(value = "/addOrModify")
	public @ResponseBody
	AjaxResult addOrModify(Bug bug) {
		if (bug.getId() != null) {
			return modify(currentService, bug, "bug");
		} else {
			Long bugid = currentService.addsAndReturnId(bug);
			if(bugid!=null&&bugid!=0){
			  SendBugMsgsThread send = new SendBugMsgsThread(currentService, bugid, Dictionary.BG_COLOR_NO_START,Dictionary.BUG_STATUS_VAITE, false, null);
			  new Thread(send).start();
			}
			/*return add(currentService, bug, "bug");*/
			return new AjaxResult(AjaxResult.STATUS_OK, null, "bug添加成功");
		}
	}

	/**
	 * 进入修改界面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/editForm")
	public String editForm(Long id, Long projId) {
		Bug bug;
		if (id != null) {
			bug = currentService.findById(id);
			WebUtil.getRequest().setAttribute("obj", bug);
		}
		WebUtil.getRequest().setAttribute("projId", projId);
		return "admin/bug-form";
	}

	/**
	 * 删除
	 */
	@RequestMapping(value = "/del")
	public @ResponseBody
	AjaxResult del(String keys) {
		return remove(currentService, keys);
	}

	/**
	 * 进入bug处理页面
	 */
	@SaveRequestToken
	@RequestMapping(value = "/toHandleBug")
	public String toHandleBug(BugFlow bugFlow) {
		String page = "admin/bug-handle";
		if (bugFlow != null && bugFlow.getBugId() != null) {
			Bug bug = currentService.findById(bugFlow.getBugId());
			WebUtil.getRequest().setAttribute("obj", bug);
			// 查看bug的操作历史
			BugFlow query = new BugFlow();
			query.setBugId(bugFlow.getBugId());
			WebUtil.getRequest().setAttribute("flowList", bugFlowService.findByModel(query));
		}
		switch (bugFlow.getType()) {
		case Dictionary.BUG_STATUS_CONFIRM:
			page = "admin/bug-confirm";
			break;
		case Dictionary.BUG_STATUS_ASSIGN:
			page = "admin/bug-assign";
			break;
		case Dictionary.BUG_STATUS_HANDLE:
			page = "admin/bug-handle";
			break;
		case Dictionary.BUG_STATUS_CLOSE:
			page = "admin/bug-close";
			break;
		case Dictionary.BUG_STATUS_ACTIVE:
			page = "admin/bug-active";
			break;
		}
		return page;
	}

	/**
	 * 处理bug
	 */
	@SaveRequestToken
	@RequestMapping(value = "/handleBug")
	public @ResponseBody
	AjaxResult handleBug(Bug bug, String content) {
		int i = 0;
		// WebUtil.getSession().getAttribute(SystemConstance.LOGIN_KEY);
		Users user = getMe();
		// 设置bug操作流水信息
		BugFlow bugFlow = new BugFlow();
		String summary = "";
		bugFlow.setBugId(bug.getId());
		bugFlow.setTime(new Date());
		bugFlow.setUserId(user.getId());
		bugFlow.setType(bug.getStatus());
		bugFlow.setContent(content);
		summary = user.getName() + bug.getStatus() + "bug";
		SendBugMsgsThread send = new SendBugMsgsThread(currentService, bug.getId(), Dictionary.BG_COLOR_FINISHED,Dictionary.BUG_STATUS_VAITE, true, null);
		switch (bug.getStatus()) {
		case Dictionary.BUG_STATUS_HANDLE:
			//获取原bug的信息
			Bug getBug = currentService.findById(bug.getId());
			// 设置bug信息：解决的话默认指派给bug的创建人
			bug.setHandleUserId(user.getId());
			bug.setUserId(getBug.getCreateUserId());
			bug.setHandleTime(new Date());
			send.setBgColor(Dictionary.BG_COLOR_FINISHED);
			send.setCreateUser(true);
			send.setTitle(Dictionary.BUG_STATUS_HANDLE);
			new Thread(send).start();
			break;
		case Dictionary.BUG_STATUS_ASSIGN:
			//改变bug的拥着者，bug的拥有者为指派人
			bug.setOwnerUserId(bug.getUserId());
			send.setBgColor(Dictionary.BG_COLOR_NO_START);
			send.setCreateUser(false);
			send.setTitle(Dictionary.BUG_STATUS_VAITE);
			new Thread(send).start();
			summary = user.getName() + bug.getStatus() + "bug给"
					+ usersService.findById(bug.getUserId()).getName();
			break;
		case Dictionary.BUG_STATUS_ACTIVE:
			// 清空解决人和解决方案为待解决
			bug.setHandleUserId(new Long(0));
			bug.setType(Dictionary.BUG_TYPE_VAITE);
			bug.setOwnerUserId(bug.getUserId());
			bug.setStatus(Dictionary.BUG_STATUS_ACTIVE);
			bug.setHandleTime(null);
			send.setBgColor(Dictionary.BG_COLOR_NO_START);
			send.setCreateUser(false);
			send.setTitle(Dictionary.BUG_STATUS_ACTIVE);
			new Thread(send).start();
			break;
		
		}
		bugFlow.setSummary(summary);
		i = currentService.handleBug(bug, bugFlow);
		if (i > 0) {
			return new AjaxResult(AjaxResult.STATUS_OK, null, "操作成功");
		}
		return new AjaxResult(AjaxResult.STATUS_ERR, null, "操作失败");
	}

	/**
	 * 进入查看界面
	 * @throws IOException 
	 */
	@SaveRequestToken
	@RequestMapping(value = "/showForm")
	public String showForm(Long id) throws IOException {
		Bug bug;
		if (id != null) {
			bug = currentService.findById(id);
			boolean flag=judgeLook(bug);
			if(flag){
				// 设置bug操作流水信息
				BugFlow bugFlow = new BugFlow();
				Users user=(Users)getMe();
				bugFlow.setBugId(bug.getId());
				bugFlow.setTime(new Date());
				bugFlow.setUserId(user.getId());
				bugFlow.setType(Dictionary.BUG_STATUS_CONFIRM);
				bugFlow.setSummary( user.getName() + "响应bug");
			    currentService.handleBug(bug, bugFlow);
			    // 查看bug的操作历史
			}
			BugFlow query = new BugFlow();
			query.setBugId(bug.getId());
			WebUtil.getRequest().setAttribute("flowList", bugFlowService.findByModel(query));  
			WebUtil.getRequest().setAttribute("obj", bug);
		}
		return "admin/bug-show";
	}
	

	public  boolean  judgeLook(Bug bug){
		boolean flag=false;
		Users user=(Users)getMe();
        Bug getBug= currentService.findById(bug.getId());
        Long userId=user.getId();
        Long ownerUserId=getBug.getOwnerUserId();
        Long firstNoticeUserId=getBug.getFirstNoticeUser();
        Long lastNoticeUserId=getBug.getLastNoticeUser();
        boolean firstEmpty= (firstNoticeUserId==null || firstNoticeUserId.equals(""))?true:false;
        if(userId.equals(ownerUserId)){
        	//责任人是当前登录的用户，没有开始响应人，视为第一次查看，第一次查看，开始响应人和最后响应人都是他自己
	        if(firstEmpty){
	        	flag=true;
	        	bug.setFirstNoticeUser(userId);
	        	bug.setFirstNoticeTime(new Date());
	        	bug.setLastNoticeUser(userId);
	        	bug.setLastNoticeTime(new Date());
	        }
	        // 责任人是当前登录的用户，有开始响应人，开始响应人和最后的响应人都和现在责任人不一致则视为更改最后响应人
	        else if(lastNoticeUserId!=userId){
	        	flag=true;
	        	bug.setLastNoticeUser(userId);
	        	bug.setLastNoticeTime(new Date());
	        }
        }
        return flag;
	}

}